/**
*@author: Miguel Soares de Lima @ 06-01-2009
*/
public class CreateNewDiscussionForumController {

	public static Boolean allowCustomer = false;
	public static Boolean allowPartner = false;  

	List<Group> allowCustomerActivated = new List<Group>();
	List<Group> allowPartnetActivated = new List<Group>();
	private String tabControl;	

    // max picture size bytes
    public final Integer MAX_SIZE = 524288;    
	//Valid size picture
	public Boolean validSizePicture = true; 
	//Valid Type Image (.jpe?g | .gif | .png)
	public Boolean validTypePicture = true;
	//Does a forum with the same name aread exists?
	public Boolean errForumNameAlreadyExists = false;
	//Discussion forum picture
	public string discussionForumPicture = ''; 

    // Members List
	public List<User> membersList = [ SELECT id, Name, FirstName, LastName, alias, Username FROM User ];
    public Attachment document = new Attachment();
	public List<Member> members = new List<Member>();
	// Edit Members
	public String editMemberId = System.currentPageReference().getParameters().get('editId');
	public DiscussionMember__c editMember = new DiscussionMember__c();
	public String imgEditMember = '';
	public Boolean itsLastAdmin = false;  
	public String editMemberRole;
	public String editMemberProfile;
	public Boolean isAdministrator = false;
	public String enabledMembersTab = 'false'; 

	//The forum list and the tab control.
	public List<DiscussionForums> discussionForumList = new List<DiscussionForums>();	
	public boolean noForums;
	public UserPermissions userPermissions = new UserPermissions();
	public String idDiscussion = System.currentPageReference().getParameters().get('id');
	//public static String removeMemberId = System.currentPageReference().getParameters().get('delId');
	public String letter = 'ALL';//System.currentPageReference().getParameters().get('ltr');
   	// SortBy
	public Boolean sortByDesc = false;
	// Order
	public String sortBy = 'User__r.Name';

   	//Set of Integers to control pagination
   	public Integer totalItemsNumber;
   	public Integer numberOfItemsToShow = 10;
   	public Integer cntPagination;
   	public Integer currentPagination = 1;
   	public Integer firstRow = 0;
    //Set of Booleans to show or not prev / next links
   	public boolean prevPageLinkShow = false;
   	public boolean prevPageShow  = false;
   	public boolean nextPageLinkShow  = false;
   	public boolean nextPageShow  = false;
	
	public List<String> lettersList = new List<String>{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};	
	//Current user id.
	public Id USERID = UserInfo.getUserId();
	//Discussion forum
	public DiscussionForum__c discussionForum = New DiscussionForum__c();


	/**
	* Constructor
	*/
	public CreateNewDiscussionForumController (){ 
		constructorFunction();
		genPermissions();
		newProfile.discussionOpenOrClosed = 'open';

		allowCustomerActivated = [ SELECT Id FROM Group WHERE Type = 'AllCustomerPortal' ];
		allowPartnetActivated = [ SELECT Id FROM Group WHERE Type = 'PRMOrganization' ];
		
		String idAct = system.currentPageReference().getParameters().get( 'id' );
		if (idAct != null){
			theDiscussion = [ SELECT Name, Description__c, PictureId__c, CreatedById, NewMemberProfile__r.Name, PublicProfile__r.Name FROM DiscussionForum__c WHERE id =: idAct limit 1];
			
			List<GroupMember> gm = new List<GroupMember>();
			Group instance = new Group();
			String instanceName = 'discussionForumSharing' + idAct;
			if(allowCustomerActivated.size() > 0 ){
				instance = [ SELECT Id FROM Group WHERE Name =: instanceName LIMIT 1 ];
				gm = [ SELECT Id FROM GroupMember WHERE GroupId =: instance.Id AND UserOrGroupId =: allowCustomerActivated[0].Id ];
				CreateNewDiscussionForumController.allowCustomer = (gm.size() > 0) ? true : false;
			}
			if(allowPartnetActivated.size() > 0 ){
				instance = [ SELECT Id FROM Group WHERE Name =: instanceName LIMIT 1 ];
				gm = [ SELECT Id FROM GroupMember WHERE GroupId =: instance.Id AND UserOrGroupId =: allowPartnetActivated[0].Id ];
				CreateNewDiscussionForumController.allowPartner = (gm.size() > 0) ? true : false;
			}
			
			String members_profile = theDiscussion.NewMemberProfile__r.Name;
			String public_profile = theDiscussion.PublicProfile__r.Name;
			if (public_profile == 'Public Profile') {
				newProfile.discussionOpenOrClosed = 'open';
			}
			else if (members_profile == 'Member Profile') {
				newProfile.discussionOpenOrClosed = 'close';
			}
			else {
				newProfile.discussionOpenOrClosed = 'private';
			}
			
			// If the user isn't owner or can manage the forum throw a CustomException
			if (!getCanEdit()) {
			    throw new CustomException('Insufficient Privileges');
			}
			enabledMembersTab = 'true';
		}
		genMembers();
	}	

	/**
	*@return String
	*/
	public String getLetter () {
		return letter;
	}	

	/**
	*@param Boolean
	*/
	public static Boolean getAllowCustomerStatic(){ 
		return allowCustomer ;
	}
	/**
	*@param Boolean
	*/
	public static Boolean getAllowPartnerStatic(){ 
		return allowPartner ;
	}

	/**
	*@param Boolean
	*/
	public void setAllowCustomer( Boolean value ){
		CreateNewDiscussionForumController.allowCustomer = value;
	}
	/** 
	*@param Boolean
	*/
	public void setAllowPartner( Boolean value ){
		CreateNewDiscussionForumController.allowPartner = value;
	}
	/**
	*@return Boolean
	*/
	public Boolean getAllowCustomer(){
		return CreateNewDiscussionForumController.allowCustomer;
	}
	/**
	*@return Boolean 
	*/
	public Boolean getAllowPartner(){
		return CreateNewDiscussionForumController.allowPartner;
	} 
	/**
	*@return Boolean
	*/
	public Boolean getAllowCustomerActivated(){
		return allowCustomerActivated.size() > 0;
	}
	/**
	*@return Boolean
	*/
	public Boolean getAllowPartnerActivated(){
		return allowPartnetActivated.size() > 0;
	}	
    /**
    *Remove discussion's avatar if exist
    *@return PageReference
    */
	public void removeAvatar()
	{
		if( this.theDiscussion != null )
		{
			Attachment avatar = new Attachment();
			DiscussionForum__c discu = new DiscussionForum__c();
			
			avatar = [ SELECT Id FROM Attachment WHERE Id =: this.theDiscussion.PictureId__c ];
			discu   = [ SELECT id, PictureId__c FROM DiscussionForum__c    WHERE Id =: this.theDiscussion.Id ];
			
			delete avatar;
			
			discu.PictureId__c = null;
			upsert discu;
			this.theDiscussion.PictureId__c = ''; 
			 System.debug('\n\n//////////////////////////\n this.theDiscussion.PictureId__c: ' + this.theDiscussion.PictureId__c + '\n//////////////////////////\n\n');
		}
	}	
	
	/**
	* Execute on construct for load forums
	*/
	public void constructorFunction () {
		totalItemsNumber = discussionForumList.size();
		if(totalItemsNumber == 0 ){
			noForums = true;
		} else {
			noForums = false;
		}
		genCntPagination();
	}

	/**
	* GETTERS METHODS
	*/
	 
	 /**
	 *@return Boolean
	 */
	 public Boolean isAdministrator(){
	 	return isAdministrator;
	 }
	 
	 /**
	 *@return Boolean
	 */
	public String getEnabledMembersTab(){
		return enabledMembersTab;
	}
	 
	/**
	* Returns tab control name
	*@return String
	*/
	public String getTabControl(){
		return tabControl;
	}
	
	/**
	* Returns DiscussionForums list
	*@return List<DiscussionForums>
	*/
	public List<DiscussionForums> getForums(){		
		return discussionForumList;
	}
	
	/**
	*@return List<user> of members
	*/
	public List<User> getMembersList(){
		return membersList;
	}

	/**
	*@return Discussion Forum
	*/
	public DiscussionForum__c getDiscussionForum(){
		return discussionForum;
	}

	
	/**
	*@return Attachment
	*/
	public Attachment getdocument () {     
		return document;
	}

	/**
	*@ Return Valid size picture
	*/
     public Boolean getValidSizePicture(){
    	return validSizePicture;
    }	
    
    /**
	*@ Return Valid type picture
	*/
     public Boolean getValidTypePicture(){
    	return validTypePicture;
    }	
    
    public boolean getErrForumNameAlreadyExists() {
    	return errForumNameAlreadyExists;
    }
    
	/**
	* Get exit forums
	*@return Boolean
	*/
	public boolean getNoForums(){
		return noForums;
	}


	/**
	* Tell if the user can edit
	* @return Boolean
	*/
	public Boolean getCanEdit ( ) {
		Boolean isOwner = (theDiscussion.CreatedById == USERID);
		return (getUserPermissions().getCanManage() || isOwner);	
	}

	/**
	*  SETTERS METHODS
	*/
	
	 /**
	 *@return Boolean
	 */
	 public void setEnabledMembersTab( String val ){
	 	enabledMembersTab = val; 	 	
	 }

	/**
	*Set User Id
	*@param Id
	*/
	public void setUserId(Id sID){
		USERID = sID;
	}
	
	/**
	*@param Attachment
	*/
	public void setdocument (Attachment attach) {
		this.document = attach;
	}
	 	
   	   	
	/**
	* Count paginator pages number.
	*/   
   	public void genCntPagination () {
   		cntPagination = (totalItemsNumber - (Math.mod(totalItemsNumber, numberOfItemsToShow)))/ numberOfItemsToShow;	
   		if (Math.mod(totalItemsNumber, numberOfItemsToShow) != 0 ) {
   			cntPagination++;
   		} 	
   	}
   	
   	/**
   	* Move to next page
   	*/
   	public void nextPage () {
   		currentPagination++;
   		firstRow = firstRow + numberOfItemsToShow;   		
   	}
   	
   	/**
   	* Move to previus page
   	*/
   	public void prevPage () {
   		currentPagination--;
   		firstRow = firstRow - numberOfItemsToShow;	
   	}
   	
   	/**
   	* Returns current pagination num
   	*@return Integer
   	*/
   	public Integer getCurrentPagination () {
   		return currentPagination;
   	}
   	
   	/**
   	* Get number of pages
   	*@return Integer
   	*/
   	public Integer getCntPagination () {
   		return cntPagination;
   	}
   	
   	/**
   	* Returns number of rows to show
   	*@return Integer
   	*/
   	public Integer getNumberOfItemsToShow () {
   		return numberOfItemsToShow;
   	}
   	
   	/**
   	* Returns current first row
   	/*@return Integer
   	*/
   	public Integer getFirstRow () {
   		return firstRow;
   	}
   	
   	/**
   	* Return boolean to show previus link
   	*@return Boolean
   	*/
	public boolean getPrevPageLinkShow () {
		if(currentPagination == 1){ 
			prevPageLinkShow = false;		
		} else {
			prevPageLinkShow = true;
		}
   		return prevPageLinkShow;
   	}
   	
   	/**
   	* Return boolean to show 
   	*@return Boolean
   	*/
   	public boolean getPrevPageShow () {
   		if(currentPagination == 1){	
   			prevPageShow = true; 
   		} else {
   			prevPageShow = false;
   		}
   		return prevPageShow;
   	}
   	
   	/**
   	* Returns boolean to show next page link
   	*@return Boolean
   	*/
   	public boolean getNextPageLinkShow () {
   		if((currentPagination == cntPagination) || (cntPagination == 0)){	
   			nextPageLinkShow = false; 
		} else { 
			nextPageLinkShow = true;
		}   		
   		return nextPageLinkShow;
   	}
   	
   	/**
   	* Returns boolean to show next page
   	*@return Boolean
   	*/
   	public boolean getNextPageShow () {
   		if((currentPagination == cntPagination) || (cntPagination == 0)){ 
   			nextPageShow = true; 
		} else { 
			nextPageShow = false;
		} 
   		return nextPageShow;
   	}

	/**
	* Inner Class to show Discussion Forum Info.
	* @param String userid The User Id, if not given , the method returns all the discussion forums available.
	* @return List<DiscussionForums> The list of Discussion Forums  
	*/	
	public List<DiscussionForums> getDiscussionForums(String userid) {
		List<DiscussionForums> discussionForumList = new List<DiscussionForums>();
		
		/**
		* If parameter is not empty, return the list of discussions.
		*/
		if(userid != ''){
			/**
			* Get user discussion List with given ID
			*/
			List<DiscussionMember__c> discussionMember = [SELECT Name, DiscussionForum__c, User__c, Id FROM DiscussionMember__c WHERE User__c =:USERID and DiscussionForum__c != null];
			List<Id> DiscussionForumIds = new List<Id>();
			for(DiscussionMember__c temp:DiscussionMember){ 
				DiscussionForumIds.add(temp.DiscussionForum__c);
			}
			
			List<DiscussionForum__c> forumList = new List<DiscussionForum__c>();
			forumList = [Select	Name, 
								Id,						
								MessageCount__c, 
								TopicCount__c,
								LastPostedMessage__c
								From DiscussionForum__c where Id IN :DiscussionForumIds];				
			if(forumList.size() >= 1 ){	
				for(DiscussionForum__c d : forumList){
					DiscussionForums discussionForumListItem = new DiscussionForums();
					System.debug( '####:' + d.MessageCount__c ); 		
					discussionForumListItem.setNumberOfMessages(d.MessageCount__c);
					discussionForumListItem.setNumberOfThreads(d.TopicCount__c);	
					discussionForumListItem.setLastPostMessage(d.LastPostedMessage__c);
					discussionForumList.add(discussionForumListItem);
				}
			}
		} else {
			/**
			* All discussions
			*/
			List<DiscussionForum__c> d = new List<DiscussionForum__c>();
			d = [Select 
						Name, 
						Id,						
						MessageCount__c, 
						TopicCount__c,
						LastPostedMessage__c
						From DiscussionForum__c ];
						
			for(DiscussionForum__c Id:d){	
				DiscussionForums discussionForumListItem = new DiscussionForums();		
				discussionForumListItem.setDiscussionId(Id.Id);
				discussionForumListItem.setNumberOfMessages(Id.MessageCount__c);
				discussionForumListItem.setNumberOfThreads(Id.TopicCount__c);	
				discussionForumListItem.setLastPostMessage(Id.LastPostedMessage__c);
				discussionForumList.add(discussionForumListItem);	
			}
		}
		return discussionForumList;
	}
	
	/**
	* Inner Class to show Discussion Forum Info.
	* @return String DiscussionName 
	* @return String DiscussionDescription 
	* @return Integer NumberOfMessages 
	* @return Integer NumberOfThreads
	* @return String LastPostMessage 
	*/
	public class DiscussionForums {
		
		String DiscussionId;
		String DiscussionName;
		String DiscussionDescription;
		Integer NumberOfMessages;
		Integer NumberOfThreads;
		String LastPostMessage;
		String Picture;
		
		/**
		*@param sDiscussionId discussion id
		*/
		public void setDiscussionId(String sDiscussionId){
        	DiscussionId = sDiscussionId;
        }
        
    	/**
    	*@param sDiscussionName discussion name
    	*/
    	public void setDiscussionName(String sDiscussionName){
        	DiscussionName = sDiscussionName;
        }
        
        /**
        *@param sDiscussionDescription discussion description
        */
        public void setDiscussionDescription(String sDiscussionDescription){
    		if(sDiscussionDescription != null){
    			 if(sDiscussionDescription.length() > 70){
    			 	DiscussionDescription = sDiscussionDescription.substring(0,67) + '...';	
    			 	//Set full description for span title
    			 	fullDescription = sDiscussionDescription;
    			 }else {
    			 	DiscussionDescription = sDiscussionDescription;
    			 }
    		}else {
    			DiscussionDescription = '';
    		}
        }
        
        public String fullDescription {set; get;}
        
        /**
        *@param sNumberOfMessages number of messages
        */
        public void setNumberOfMessages(Double sNumberOfMessages){
        	NumberOfMessages = ( sNumberOfMessages == null ) ? 0 : sNumberOfMessages.intValue();
        }

        /**
        *@param sNumberOfThreads number of threads
        */
        public void setNumberOfThreads(Double sNumberOfThreads){
        	NumberOfThreads = ( sNumberOfThreads == null ) ? 0 : sNumberOfThreads.intValue();
        }
        
        /**
        *@param sLastPostMessage last posted message
        */
        public void setLastPostMessage(Id sLastPostMessage){
        	LastPostMessage = lastPostInfoString(sLastPostMessage);
        }
        
        /**
        *@param discussionAvatar discussion avatar
        */
        public void setPicture(String discussionAvatar){
        	Picture = discussionAvatar;
        }
        
		/**
		*@return discussion id
		*/
		public String getDiscussionId() {
	    	return DiscussionId;
		}
		
        /**
        *@return discussion name
        */
        public String getDiscussionName() {
	    	return DiscussionName;
		}		
        
        /**
        *@return discussion description
        */
        public String getDiscussionDescription() {
	    	return DiscussionDescription;
		}
		
		/**
		*@return number of messages
		*/
		public Integer getNumberOfMessages() {
	    	return NumberOfMessages;
		}
		
		/**
		*@return number of threads
		*/
		public Integer getNumberOfThreads() {
	    	return NumberOfThreads;
		}	
		
		/**
		*@return last posted message
		*/
		public String getLastPostMessage() {
	    	return LastPostMessage;
		}
		
		/**
		*@return discussion avatar
		*/
		public String getImage(){			
		  if(Picture == null)
		  	return '';
		  else
		  	return Picture;				
		}
		
		/**
		* Method to convert dates.
		* @return String datestring The string of the lastest reply. 
		*/
		public String lastPostInfoString(Id dm){
			String lastPostString = '';
			String message = '';
			
			if (dm != null){
				List<DiscussionMessage__c> dms = new List<DiscussionMessage__c>();
				dms = [ Select 
						LastModifiedDate, 
						DiscussionTopic__r.Subject__c, 
						DiscussionTopic__c,
						PostedBy__r.Name, 
						PostedBy__r.Id,
						PostedBy__c From DiscussionMessage__c where id =: dm];
						
				if(dms.size() > 0){
					DiscussionMessage__c d = dms[0];
					Integer today = (System.now()).day();
					String dateInfo;
					
					if(today == (d.LastModifiedDate).day()){
						dateInfo = 'Today, at ' + (d.LastModifiedDate).format('HH:mm') + ' ' + (d.LastModifiedDate).format('aa');	
					} else {
						dateInfo = '' + (d.LastModifiedDate).day() + ' of '+ (d.LastModifiedDate).format('MMMM') + ' at ' +(d.LastModifiedDate).format('HH:mm') + ' ' + (d.LastModifiedDate).format('aa');
					}
					
					message = d.DiscussionTopic__r.Subject__c;
					
					if(message != null && message.length() > 25){
						message = message.substring(0,25) + '...';
					}
					
			 		lastPostString = ' ' + dateInfo + ' in ' + message + ' by ' + d.PostedBy__r.Name;
				} else {
					lastPostString = 'This Forum has no messages yet.';
				}
			} else {
				lastPostString = 'This Forum has no messages yet.';
			}
			return lastPostString;
		}	
	}
	
	
	public Integer rowsCodeCoverage = 300;
	
	/**
	* Get rows for code coverage
	*@return Integer
	*/
	public Integer getrowsCodeCoverage(){
		return rowsCodeCoverage;
	} 
	
	/**
	* Set number of row (for code coverage use)
	*@param Integer
	*/
	public void setRowsCodeCoverage(Integer value){
		rowsCodeCoverage = value;
	}
	
	/**
	* Returns ActiveUser list
	*@return List<ActiveUser>
	*/
	public List<ActiveUser> getMostActiveUsers(){
		Date first = System.today().toStartOfWeek();
    	Datetime firstWeekDay = Datetime.newInstance(first.year(), first.month(), first.day(), 0, 0, 0);
    	Datetime lastWeekDay = firstWeekDay.addDays(7);
		Map<Id, ActiveUser> tempmap = new Map<Id, ActiveUser>();
		List<ActiveUser> mostActiveUsers = new List<ActiveUser>();
		Integer i;
		
		for(DiscussionForum__c disc : [Select Name, Id, MessageCount__c, TopicCount__c, LastPostedMessage__c, CreatedDate, CreatedBy.Name, CreatedById From DiscussionForum__c limit : rowsCodeCoverage]){
			
			if(tempmap.containsKey(disc.CreatedById)){
				ActiveUser activeUser = tempmap.get(disc.CreatedById);
				Integer tempCount = activeUser.getMostActive() + 1;
				activeUser.setMostActive(tempCount); 
				tempmap.put(disc.CreatedById, activeUser);
			}else {
				ActiveUser activeUser = new ActiveUser();
				activeUser.setMostActive(1);
				activeUser.setId (disc.CreatedById);
				activeUser.setName(disc.CreatedBy.Name);
				tempmap.put(disc.CreatedById, activeUser);
			}
		}
		List<ActiveUser> activeUserList = tempmap.values();		 				
		this.sortResult(activeUserList);
		for(i = 0; i <= 5; i++ ){
			if(i < activeUserList.size()){
				activeUserList[i].commentCount();
				mostActiveUsers.add(activeUserList[i]);
			}
		}
		return mostActiveUsers;
	}
	
	/**
	* Returns ActiveUser sorted list
	*@param List<ActiveUser> unsorted list
	*@return List<ActiveUser> sorted list
	*/
	public List<ActiveUser> sortResult (List<ActiveUser> result) {
 		Integer n;
 		Integer i;
 		Integer j;
 		n = result.size() - 1;	
 		for (i = 1; i <= n; i++) {	
 			for (j = n; j >= i ; j--) {
 				if (result.get(j).getMostActive() >= result.get(j - 1).getMostActive()) {
 					ActiveUser tempActiveUser;
 					tempActiveUser = result.get(j - 1);
 					result.set(j - 1, result.get(j));
 					result.set(j, tempActiveUser); 	
 				}	
 			}
 		}
 		return result;
 	}	

    /**
    * Class discussionProfile
    */
    public class discussionProfile {
    	public String publicProfileOpen { set; get; }
    	public String newProfileOpen { set; get; }
    	public String publicProfileClosed { set; get; }
    	public String discussionOpenOrClosed { set; get; }     	
    }
    
    discussionProfile newProfile = new discussionProfile();
    
    public discussionProfile getNewProfile(){
    	return newProfile;
    }
    public void setNewProfile( DiscussionProfile objProfile )
    {
    	newProfile = objProfile;
    }
	/**
	* Save new discussion forum to data base
	*/
	
	public DiscussionForum__c theDiscussion= New DiscussionForum__c();
	/**
    * Set Discussion
    *@param Discussion__c t
    */
    public void setDiscussion(DiscussionForum__c t){
    	theDiscussion= t;
    }
    
	/**
	*@return discussion forum instance
	*/
	public DiscussionForum__c getDiscussion(){
    	return theDiscussion;
	}
	 
	/**
	*@return PageReference
	*/
	public PageReference saveDiscussionForum()
	{
		//Stub profiles
		genProfiles();

		validSizePicture = true;
		validTypePicture = true; 
		errForumNameAlreadyExists = false;
		
		if (document.name == null || document.name == '' || document.BodyLength > MAX_SIZE || 
				!(document.ContentType == 'image/jpeg' || document.ContentType == 'image/pjpeg' || document.ContentType == 'image/gif' 
				|| document.ContentType == 'image/png' || document.ContentType == 'image/x-png')) {
			if (document.BodyLength > MAX_SIZE) {
				validSizePicture = false;
			}
			if (!(document.name == null || document.name == '') && !(document.ContentType == 'image/jpeg' || document.ContentType == 'image/pjpeg' || 
					document.ContentType == 'image/gif' || document.ContentType == 'image/png')) {
				validTypePicture = false;
			} 
			document = new Attachment();
			if (!validSizePicture || !validTypePicture) {
				return null;
			}	
		} 
		
		if (theDiscussion.Id == null) {
			DiscussionForum__c[] forums = [ SELECT id FROM DiscussionForum__c WHERE Name =: theDiscussion.Name ];
			
			if (forums != null && forums.size() > 0) {
				errForumNameAlreadyExists = true;
				return null;
			}
		}
		 
		if(newProfile.discussionOpenOrClosed == 'open'){
			theDiscussion.PublicProfile__c = [ SELECT id FROM DiscussionProfile__c WHERE Name =: 'Public Profile' ].id;
			theDiscussion.Type__c = 'open';			
		}else if (newProfile.discussionOpenOrClosed == 'close') {
			theDiscussion.NewMemberProfile__c = [ SELECT id FROM DiscussionProfile__c WHERE Name =: 'Member Profile' limit 1 ].id;
			theDiscussion.PublicProfile__c = null;
			theDiscussion.Type__c = 'close';			
		}else if (newProfile.discussionOpenOrClosed == 'private'){
			theDiscussion.Type__c = 'private';
			theDiscussion.PublicProfile__c = null;
			theDiscussion.NewMemberProfile__c = null;
		}
		
		// Set boolean to true for execute triggers
		TeamUtil.setIsRunnig( true );
		
		if(theDiscussion.Id == null){
    		insert theDiscussion;	
		}else {
    		update theDiscussion;
    	}
		
		if(document.name != null && document.name != ''){
    		document.ParentId = theDiscussion.Id;
	    	insert document;
    		theDiscussion.PictureId__c = document.Id; 
    		update theDiscussion;	
		}
			
		
		PageReference pageRef = new PageReference('/apex/discussionTopics?id=' + theDiscussion.Id);
    	pageRef.setRedirect(false);
    	return pageRef;
	}
	
	/**
	* Add Members method
	*@return page reference for forward to edit mode
	*/
	public pageReference saveAndAddMembers(){
		PageReference nextAcction = saveDiscussionForum();
		PageReference pageRef = new PageReference('/apex/CreateNewDiscussionForum?id=' + theDiscussion.Id + '&add=true');
		pageRef.setRedirect(true);
		if (nextAcction == null) {
			return null;
		}
		else {
			return pageRef;
		}
	}
	
	/**
	* Save and redirect
	*/
	public boolean toListMembers = false;
	public boolean getToListMembers(){
			return toListMembers;
	}
	
	/**
	*@return page reference to forum topics view
	*/
	public pageReference saveAndRedirect(){
		pageReference nextAction = saveDiscussionForum();
        if(nextAction != null) {
        	nextAction.setRedirect(true);
        }
        /* toListMembers = true; */
        enabledMembersTab = 'true';
        return nextAction;
	}
	
	
	/**
	*@return page reference to show member list
	*/
	public pageReference showMembersList(){	
        PageReference pageRef = new PageReference('/apex/CreateNewDiscussionForum?id=' + system.currentPageReference().getParameters().get( 'id' ));
        pageRef.setRedirect(true);
        toListMembers = true;
        return pageRef;
	}

	/**
	* Class for encapsulate active Users instance
	*/
	public class ActiveUser{
		
		public String userPicture;
		public Integer mostActive;
		public String name;
		public Integer commentsCount;
		public String id;

		public ActiveUser(){}
		
		public ActiveUser(String id){}
		
		/**
		* Returns messages count
		*/
		public void commentCount(){
			this.commentsCount = [Select count() From DiscussionMessage__c where PostedBy__c =: id];	
		}
		
		/**
		*@return number of most active users
		*/
		public Integer getMostActive(){
			return 	mostActive;
		}	
		
		/**
		*@return user name
		*/
		public String getName(){
			return 	name;
		}	
		
		/**
		*@return user id
		*/
		public String getId(){
			return 	id;
		}	
		
		/**
		*@return number of comments
		*/
		public Integer getCommentsCount(){
			return 	commentsCount;
		}
		
		/**
		*@return user avatar
		*/
		public String getPicture(){
			return this.userPicture;
		}
		
		/**
		*@param mActive num of most active users
		*/
		public void setMostActive(Integer mActive){
			mostActive = mActive;
		}
		
		/**
		*@param sName user name
		*/
		public void setName(String sName){
			name = sName;
		}
		
		/**
		*@param id user id
		*/
		public void setId(String id){
			this.id = id;
		}
		
		/**
		*@param countComments number of comments
		*/
		public void setCommentsCount(Integer countComments){
			commentsCount = countComments;
		}
	}

	/**
	*Generate the profiles 
	*/
	public void genProfiles(){
		Integer cnt;
		cnt = [select count() from DiscussionProfile__c where Name = 'Member Profile'];	
       	if(cnt == 0){
       	    DiscussionProfile__c DiscussionForumProfile = new DiscussionProfile__c();
       	    DiscussionForumProfile.Name = 'Member Profile';
       	    DiscussionForumProfile.PostDiscussionTopicReplies__c = true;
       	    DiscussionForumProfile.ManageDiscussionForums__c = false;
       	    DiscussionForumProfile.CreateDiscussionTopics__c = true;
       	    insert DiscussionForumProfile;
       	}
      	cnt = [select count() from DiscussionProfile__c where Name = 'Public Profile'];
       	if(cnt == 0){
       	    DiscussionProfile__c DiscussionForumProfile = new DiscussionProfile__c();
       	    DiscussionForumProfile.Name = 'Public Profile';
       	    DiscussionForumProfile.PostDiscussionTopicReplies__c = true;
       	    DiscussionForumProfile.ManageDiscussionForums__c = false;
       	    DiscussionForumProfile.CreateDiscussionTopics__c = false;
       	    insert DiscussionForumProfile;
       	}
       	cnt = [select count() from DiscussionProfile__c where Name = 'DiscussionForum Administrator'];
       	if(cnt == 0){
       	    DiscussionProfile__c DiscussionForumProfile = new DiscussionProfile__c();
       	    DiscussionForumProfile.Name = 'DiscussionForum Administrator';
       	    DiscussionForumProfile.PostDiscussionTopicReplies__c = true;
       	    DiscussionForumProfile.ManageDiscussionForums__c = true;
       	    DiscussionForumProfile.CreateDiscussionTopics__c = true;
       	    insert DiscussionForumProfile;
       	}
	}

	/**
	*@return String ID
	*/	
	public String getDiscussionId () {
		return idDiscussion;	
	}

	/**
	*@return Boolean
	*/
	public Boolean getSortByDesc () {
		return !sortByDesc;
	}
	
	/**
	*@param s sort by field
	*/
	public void setSortBy (String s){
		sortBy = s;	
	}
	
	/**
	*@return String
	*/
	public String getSortBy () {
		String sbCol = '';
		if (sortBy == null || sortBy == 'User__r.Name') 
			sbCol = 'name';	
		if (sortBy == 'User__r.Alias') 
			sbCol = 'alias';	
		if (sortBy == 'User__r.Username') 
			sbCol = 'username';	
		if (sortBy == 'DiscussionProfile__r.Name') 
			sbCol = 'profile';	

		return sbCol;
	}
	
	/**
	* Return list of members
	*@return List<Member>
	*/
	public List<Member> getMembers () {
		return members;
	}
	
	/**
	* Refresh member list
	*@void
	*/
	public void refresh() {genMembers();}
	
	/**
	* Generate user permissions
	*@void
	*/
	public void genPermissions() {
		userPermissions.setId(UserInfo.getUserId());
		userPermissions.setTeam(idDiscussion);
		userPermissions.setObjectType('Discussion');
		userPermissions.setPermissions();		
	}
	
	/**
	* Return the Namespace Prefix
	*@return String
	*/
	public String getNamespace () {
        return TeamUtil.getNamespace();
    }
	
	/**
	* Asign the Name of the user to remove
	*@void
	*/
	/*
	public void assignRemoveId () {
		if (System.currentPageReference().getParameters().get('delId') != null) {
			removeMemberId = System.currentPageReference().getParameters().get('delId');	
		}
		
	/**	delName = [select User__r.Name from DiscussionMember__c 
	*				where User__c =: removeMemberId and DiscussionForum__c =: idDiscussion].User__r.Name;
	}
	*/
	
	/**
	* Stuff before edit
	*@void
	*/
	public void assignEditId () {
		if (System.currentPageReference().getParameters().get('editId') != null) {
			editMemberId = 	System.currentPageReference().getParameters().get('editId');
		}
		
		List<DiscussionMember__c> auxList = [select id, User__r.name, DiscussionProfile__c, User__r.companyName, User__r.Title  from DiscussionMember__c where User__c =: editMemberId and DiscussionForum__c =: idDiscussion];
		if (auxList.size() > 0) {
			editMember = auxList[0];
		}
		
		Integer countAdmin = [select count() from DiscussionMember__c where DiscussionForum__c = :idDiscussion];
		Boolean isAdmin = [select DiscussionProfile__r.ManageDiscussionForums__c from DiscussionMember__c where DiscussionForum__c =:idDiscussion and User__c=:editMemberId limit 1].DiscussionProfile__r.ManageDiscussionForums__c;
		
		itsLastAdmin = (editMemberId == UserInfo.getUserId()) && isAdmin;
		editMemberProfile = editmember.DiscussionProfile__c;
	}
	
	/**
	* Return user permissions
	*@return UserPermissions
	*/
	public UserPermissions getUserPermissions () {
		return userPermissions;
	}		
	
	/**
	* Return all Profiles
	*@return List<DiscussionProfile__c>
	*/
	public List<DiscussionProfile__c> getDiscussionEditProfiles () {
		return [select Name, id from DiscussionProfile__c order by Name];
	}
	
	/**
	* Search members
	*@void
	*/
	public void genMembers () {
		List<Member> membersList = new List<Member>();
		
		sortByDesc = false;
		sortBy = 'User__r.Name';
		
		if(System.currentPageReference().getParameters().get('ltr') != null)
			letter = System.currentPageReference().getParameters().get('ltr');
				
		if (letter == null || letter == '' || letter== 'ALL') {
			for (DiscussionMember__c item: [select id, User__r.FirstName, User__r.LastName, User__r.Alias, User__r.Username, DiscussionProfile__r.Name from DiscussionMember__c where DiscussionForum__c =:idDiscussion ORDER BY User__r.Name ]) {
				Member memberItem = new Member();
				
				memberItem.setName( item.User__r.FirstName + ' ' + item.User__r.LastName );
				memberItem.setUserId(item.User__r.Id);
				memberItem.setAlias( item.User__r.Alias );
				memberItem.setUsername( item.User__r.Username );
				memberItem.setProfile( item.DiscussionProfile__r.Name );
				memberItem.setDiscussionMemberId(item.id);
				membersList.add(memberItem);
			}
		}else {
			for (DiscussionMember__c item: [select id, User__r.FirstName, User__r.LastName, User__r.Alias, User__r.Username, DiscussionProfile__r.Name from DiscussionMember__c where Name like :(letter + '%') and DiscussionForum__c =:idDiscussion ORDER BY User__r.Name ]) {
				Member memberItem = new Member();
				
				memberItem.setName( item.User__r.FirstName + ' ' + item.User__r.LastName );
				memberItem.setUserId(item.User__r.Id);
				memberItem.setAlias( item.User__r.Alias );
				memberItem.setUsername( item.User__r.Username );
				memberItem.setProfile( item.DiscussionProfile__r.Name );
				memberItem.setDiscussionMemberId(item.id);	
				membersList.add(memberItem);
			}
		}	
		totalItemsNumber = membersList.size();
		if (totalItemsNumber == 0 ) {
			cntPagination = 0;	
			firstRow = 0;
			currentPagination = 1;
		}else {
			firstRow = 0;
			currentPagination = 1;
			genCntPagination();	
		}
		members = membersList;
	}	
	
	/**
	* Return list with letters and if contain Discussion Members
	*@return List<Letters>
	*/
	public List<Letters> getLetterFilter () {
		List<Letters> letterFilter = new List<Letters>();
   		for (String item : lettersList) {
   			Letters currentLetter = new Letters();
   			Integer cntMembers = [select count() from DiscussionMember__c where Name like :(item + '%') and DiscussionForum__c =:idDiscussion];
   			currentLetter.setLetter(item);
   			currentLetter.setContainMembers(cntMembers);
   			letterFilter.add(currentLetter);
   		}
   		return letterFilter;		
	}

	/**
	 * This is a temporary method to cover us until dynamic apex is back.  This will use hard coded
	 * SOQL statements in place of the dynamic statements
	 */
	public void sortList () {
		List<Member> membersList = new List<Member>();
		if (sortBy == System.currentPageReference().getParameters().get('sb')) {
			sortByDesc = !sortByDesc;
		}else {
			sortByDesc = false;
		}
		
		//Sort param
		if(System.currentPageReference().getParameters().get('sb') != null)
			sortBy = System.currentPageReference().getParameters().get('sb');
		
		List<DiscussionMember__c> memberResultList = new List<DiscussionMember__c>();

		if (sortByDesc) {
			if (letter == null || letter == '' || letter== 'ALL') {
				if (sortBy == 'User__r.Name') {
					memberResultList = [select id, User__r.Name, User__r.Alias, User__r.Username,User__r.Id,  DiscussionProfile__r.Name
										from DiscussionMember__c 
										where DiscussionForum__c =: idDiscussion and User__r.IsActive != false
										order by User__r.Name desc];
				
				}
				if (sortBy == 'User__r.Alias') {
					memberResultList = [select id, User__r.Name, User__r.Alias, User__r.Username,User__r.Id,  DiscussionProfile__r.Name
										from DiscussionMember__c 
										where DiscussionForum__c =: idDiscussion and User__r.IsActive != false
										order by User__r.Alias desc];
					System.debug('Here:::');
				
				}
				if (sortBy == 'User__r.Username') {
					memberResultList = [select id, User__r.Name, User__r.Alias, User__r.Username,User__r.Id,  DiscussionProfile__r.Name
										from DiscussionMember__c 
										where DiscussionForum__c =: idDiscussion //and User__r.IsActive != false
										order by User__r.Username desc];
				
				}
				if (sortBy == 'DiscussionProfile__r.Name') {
					memberResultList = [select id, User__r.Name, User__r.Alias, User__r.Username,User__r.Id,  DiscussionProfile__r.Name 
										from DiscussionMember__c 
										where DiscussionForum__c =: idDiscussion //and User__r.IsActive != false
										order by DiscussionProfile__r.Name desc];						
				}
			}else {

					if (sortBy == 'User__r.Name') {
						memberResultList = [ select id, User__r.Name, User__r.Alias, User__r.Username,User__r.Id,  DiscussionProfile__r.Name 
											from DiscussionMember__c 
											where User__r.Name like: (letter + '%') and DiscussionForum__c =: idDiscussion //and User__r.IsActive != false
											order by User__r.Name desc];					
					}
					if (sortBy == 'User__r.Alias') {
						memberResultList = [ select id, User__r.Name, User__r.Alias, User__r.Username,User__r.Id,  DiscussionProfile__r.Name 
											from DiscussionMember__c 
											where User__r.Name like: (letter + '%') and DiscussionForum__c =: idDiscussion //and User__r.IsActive != false
											order by User__r.Name desc];					
					}
					if (sortBy == 'User__r.Username') {
						memberResultList = [ select id, User__r.Name, User__r.Alias, User__r.Username,User__r.Id,  DiscussionProfile__r.Name 
											from DiscussionMember__c 
											where User__r.Name like: (letter + '%') and DiscussionForum__c =: idDiscussion //and User__r.IsActive != false
											order by User__r.Name desc];					
					}
					if (sortBy == 'DiscussionProfile__r.Name') {
						memberResultList = [select id, User__r.Name, User__r.Alias, User__r.Username,User__r.Id,  DiscussionProfile__r.Name 
											from DiscussionMember__c 
											where User__r.Name like: (letter + '%') and DiscussionForum__c =: idDiscussion //and User__r.IsActive != false
											order by DiscussionProfile__r.Name desc];						
					}
				
			}
		}else {
			if (letter == null || letter == '' || letter== 'ALL') {
				if (sortBy == 'User__r.Name') {
					memberResultList = [select id, User__r.Name, User__r.Alias, User__r.Username,User__r.Id,  DiscussionProfile__r.Name
										from DiscussionMember__c 
										where DiscussionForum__c =: idDiscussion //and User__r.IsActive != false
										order by User__r.Name asc];
				}
				if (sortBy == 'User__r.Alias') {
					memberResultList = [select id, User__r.Name, User__r.Alias, User__r.Username,User__r.Id,  DiscussionProfile__r.Name
										from DiscussionMember__c 
										where DiscussionForum__c =: idDiscussion //and User__r.IsActive != false
										order by User__r.Alias asc];
				}
				if (sortBy == 'User__r.Username') {
					memberResultList = [select id, User__r.Name, User__r.Alias, User__r.Username,User__r.Id,  DiscussionProfile__r.Name
										from DiscussionMember__c 
										where DiscussionForum__c =: idDiscussion //and User__r.IsActive != false
										order by User__r.Username asc];
				}
				if (sortBy == 'DiscussionProfile__r.Name') {
					memberResultList = [select id, User__r.Name, User__r.Alias, User__r.Username,User__r.Id,  DiscussionProfile__r.Name
										from DiscussionMember__c 
										where DiscussionForum__c =: idDiscussion //and User__r.IsActive != false
										order by DiscussionProfile__r.Name];						
				}
			}else {
				if (sortBy == 'User__r.Name') {
					memberResultList = [select id, User__r.Name, User__r.Alias, User__r.Username,User__r.Id,  DiscussionProfile__r.Name
										from DiscussionMember__c 
										where User__r.Name like: (letter + '%') and DiscussionForum__c =: idDiscussion and User__r.IsActive != false
										order by User__r.Name asc];					
				}
				if (sortBy == 'User__r.Alias') {
					memberResultList = [select id, User__r.Name, User__r.Alias, User__r.Username,User__r.Id,  DiscussionProfile__r.Name
										from DiscussionMember__c 
										where User__r.Name like: (letter + '%') and DiscussionForum__c =: idDiscussion and User__r.IsActive != false
										order by User__r.Alias asc];					
				}
				if (sortBy == 'User__r.Username') {
					memberResultList = [select id, User__r.Name, User__r.Alias, User__r.Username,User__r.Id,  DiscussionProfile__r.Name
										from DiscussionMember__c 
										where User__r.Name like: (letter + '%') and DiscussionForum__c =: idDiscussion and User__r.IsActive != false
										order by User__r.Username asc];					
				}
				if (sortBy == 'DiscussionProfile__r.Name') {
					memberResultList = [select id, User__r.Name, User__r.Alias, User__r.Username,User__r.Id,  DiscussionProfile__r.Name
										from DiscussionMember__c 
										where User__r.Name like: (letter + '%') and DiscussionForum__c =: idDiscussion and User__r.IsActive != false
										order by DiscussionProfile__r.Name asc];						
				}
			}			
		}
				 
		for (DiscussionMember__c item: memberResultList) {
			Member memberItem = new Member();
			memberItem.setName(item.User__r.Name);
			memberItem.setAlias(item.User__r.Alias);
			memberItem.setUsername(item.User__r.Username);
			memberItem.setProfile(item.DiscussionProfile__r.Name);
			memberItem.setUserId(item.User__r.Id);	
			memberItem.setMemberImg(item.User__r.Id);
			membersList.add(memberItem);
		}
			
		totalItemsNumber = membersList.size();
		if (totalItemsNumber == 0 ) {
			cntPagination = 0;	
			firstRow = 0;
			currentPagination = 1;
		}else {
			firstRow = 0;
			currentPagination = 1;
			genCntPagination();	
		}
		members = membersList;	
	}

	public class Member {
		
		String alias;
		String username;
		String memberImg;
		String title;
		String profile;
		String name;
		String userId;
		String discussionMemberId;
		Boolean admin;
		
		/**
		*@return String
		*/
		public String getAlias () {
			return alias;
		}
		
		/**
		*@Param String Alias
		*/
		public void setAlias( String als ){
			this.alias = als;		
		}

		/**
		*@Param String Username
		*/
		public void setUsername( String usName ){
			this.username = usName;		
		}
		
		/**
		*@return String
		*/
		public String getUsername () {
			return username;	
		}
		
		/**
		*@return String ID
		*/
		public String getUserId (){
			return userId;
		}
		
		/**
		*@return String ID
		*/
		public String getDiscussionMemberId (){
			return discussionMemberId;
		}
		
		/**
		*@param String ID
		*/
		public void setDiscussionMemberId (String discussionMemberId){
			this.discussionMemberId = discussionMemberId;
		}
		
		/**
		*@return String
		*/
		public String getName () {
			return name;
		}
		
		/**
		*@return String
		*/
		public String getMemberImg () {
			return memberImg;
		}
			
		/**
		*@return String
		*/
		public String getTitle () {
			return title;
		}
		
		/**
		*@return String
		*/
		public String getProfile () {
			return profile;
		}
		
		/**
		*@param String ID
		*/
		public void setUserId (String userId) {
			this.userId = userId;
		}
		
		/**
		*@param String name
		*/
		public void setName (String name) {
			this.name = name;
		}
		
		/**
		*@param String idMember
		*/
		public void setMemberImg (String memberId) {
			

		}
		
		/**
		*@param String
		*/
		public void setProfile (String profile) {
			this.profile = profile;
		}
		
		/**
		*@param String
		*/
		public void setTitle (String title) {
			this.title = title;
		}
		
		/**
		*@param Boolean
		*/
		public void setAdmin (Boolean admin) {
			this.admin = admin;	
		}
		
		/**
		*@return Boolean
		*/
		public Boolean getAdmin () {
			return admin;
		}
	}
	
	/**
	* Inner class for Letters type
	*/
	public class Letters {
		String letter;
		Boolean containMembers;
		
		/**
		*@param String
		*/
		public void setLetter (String letter) {
			this.letter = letter;
		}
		
		/**
		*@return String
		*/
		public String getLetter () {
			return letter;
		}
		
		/**
		*@param Integer
		*/
		public void setContainMembers (Integer cntMembers) {
			this.containMembers = ( cntMembers == 0 );
		}
		
		/**
		*@return Boolean
		*/
		public Boolean getContainMembers () {
			return containMembers;
		}
	}
	
}